#import "SMMineViewController.h"
#import <Masonry/Masonry.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "SMMineMenuCell.h"
#import "SMMineRecentCell.h"
// 子页面
#import "SMMineFavoritesViewController.h"
#import "SMMineFollowsViewController.h"
#import "SMMineFansViewController.h"
#import "SMMineOrdersViewController.h"
#import "SMMineAddressViewController.h"
#import "SMMineWalletViewController.h"
#import "SMMineMessagesViewController.h"
#import "SMMineHistoryViewController.h"
#import "SMMineInviteViewController.h"
#import "SMMineSupportViewController.h"
#import "SMMineAboutViewController.h"
#import "SMMineSettingsViewController.h"

static NSString * const kMenuCellId   = @"SMMineMenuCell";
static NSString * const kRecentCellId = @"SMMineRecentCell";

@interface SMMineViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, strong) UIScrollView *scroll;
@property(nonatomic, strong) UIView *content;
@property (nonatomic, strong) MASConstraint *menuGridHeightConstraint;

// 顶部资料卡
@property(nonatomic, strong) UIView *headerBg;     // 渐变背景容器
@property(nonatomic, strong) UIView *card;         // 白色圆角卡片
@property(nonatomic, strong) UIImageView *avatar;
@property(nonatomic, strong) UILabel *nameL;
@property(nonatomic, strong) UILabel *signL;
@property(nonatomic, strong) UIButton *settingsBtn;

// 统计
@property(nonatomic, strong) UIStackView *statStack;
@property (nonatomic, strong) UIView *headerUnderlay;          // 顶部渐变底图（不在scroll里）
@property (nonatomic, strong) NSLayoutConstraint *headerHCons;  // 高度约束

// 宫格功能
@property(nonatomic, strong) UICollectionView *menuGrid;
@property(nonatomic, strong) NSArray<NSDictionary *> *menuData;

// 最近浏览/猜你喜欢
@property(nonatomic, strong) UILabel *recentTitle;
@property(nonatomic, strong) UICollectionView *recentList;
@property(nonatomic, strong) NSArray<NSDictionary *> *recentData;

@end

@implementation SMMineViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}




- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的";
    self.view.backgroundColor = UIColor.systemGroupedBackgroundColor;
    [self buildUI];
    [self mockDataAndRender];
}
- (void)viewSafeAreaInsetsDidChange {
    [super viewSafeAreaInsetsDidChange];
    CGFloat safeTop = self.view.safeAreaInsets.top; // 刘海/状态栏高度
    // 220 是你原头部视觉高度（可以按你设计调整）
    self.headerHCons.constant = safeTop + 220.0;
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
}

#pragma mark - UI

- (void)buildUI {
    
    
    if (@available(iOS 11.0, *)) {
        self.scroll.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.extendedLayoutIncludesOpaqueBars = YES;

    // ① 顶部渐变底图，放在 self.view（不滚动）
    self.headerUnderlay = [UIView new];
    self.headerUnderlay.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerUnderlay];
    [NSLayoutConstraint activateConstraints:@[
        [self.headerUnderlay.topAnchor constraintEqualToAnchor:self.view.topAnchor],
        [self.headerUnderlay.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.headerUnderlay.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor]
    ]];
    // 高度先给一个默认值，稍后在 viewSafeAreaInsetsDidChange 里按 safeArea 动态更新
    self.headerHCons = [self.headerUnderlay.heightAnchor constraintEqualToConstant:220];
    self.headerHCons.active = YES;

    [self addGradientTo:self.headerUnderlay]; // 直接复用你原来的渐变方法

    // ② 再加 ScrollView（盖在渐变上面）
    _scroll = [UIScrollView new];
    _scroll.alwaysBounceVertical = YES;
    [self.view addSubview:_scroll];
    [_scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];

    _content = [UIView new];
    [_scroll addSubview:_content];
    [_content mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scroll);
        make.width.equalTo(self.scroll);
    }];

    // 顶部渐变背景
    _headerBg = [UIView new];
    _headerBg.backgroundColor = UIColor.clearColor;
    [_content addSubview:_headerBg];
    [_headerBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.content);
        make.height.mas_equalTo(220);
    }];
    [self addGradientTo:_headerBg];

    // 顶部设置按钮
    _settingsBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    if (@available(iOS 13.0, *)) {
        [_settingsBtn setImage:[UIImage systemImageNamed:@"gearshape"] forState:UIControlStateNormal];
    } else {
        [_settingsBtn setTitle:@"设置" forState:UIControlStateNormal];
    }
    _settingsBtn.tintColor = UIColor.whiteColor;
    [_settingsBtn addTarget:self action:@selector(tapSettings) forControlEvents:UIControlEventTouchUpInside];
    [_headerBg addSubview:_settingsBtn];
    [_settingsBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerBg.mas_top).offset(14 + UIApplication.sharedApplication.statusBarFrame.size.height * 0.0); // 简化处理
        make.right.equalTo(self.headerBg).offset(-16);
        make.width.height.mas_equalTo(30);
    }];

    // 白色圆角资料卡
    _card = [UIView new];
    _card.backgroundColor = UIColor.secondarySystemBackgroundColor;
    _card.layer.cornerRadius = 16;
    _card.layer.masksToBounds = YES;
    _card.layer.shadowColor = [UIColor colorWithWhite:0 alpha:0.2].CGColor;
    _card.layer.shadowOpacity = 0.08;
    _card.layer.shadowRadius = 12;
    _card.layer.shadowOffset = CGSizeMake(0,6);
    [_content addSubview:_card];
    [_card mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.content).offset(90); // 距页面顶部 90，叠在渐变上（看起来一样）
        make.left.equalTo(self.content).offset(16);
        make.right.equalTo(self.content).offset(-16);
    }];

    _avatar = [UIImageView new];
    _avatar.layer.cornerRadius = 34;
    _avatar.clipsToBounds = YES;
    _avatar.layer.borderWidth = 2;
    _avatar.layer.borderColor = UIColor.whiteColor.CGColor;
    _avatar.contentMode = UIViewContentModeScaleAspectFill;

    _nameL = [UILabel new];
    _nameL.font = [UIFont systemFontOfSize:18 weight:UIFontWeightSemibold];
    _nameL.textColor = UIColor.labelColor;

    _signL = [UILabel new];
    _signL.font = [UIFont systemFontOfSize:13];
    _signL.textColor = UIColor.secondaryLabelColor;

    [_card addSubview:_avatar];
    [_card addSubview:_nameL];
    [_card addSubview:_signL];

    [_avatar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.card).offset(16);
        make.left.equalTo(self.card).offset(16);
        make.width.height.mas_equalTo(68);
    }];
    [_nameL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.avatar.mas_top).offset(6);
        make.left.equalTo(self.avatar.mas_right).offset(12);
        make.right.lessThanOrEqualTo(self.card).offset(-16);
    }];
    [_signL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameL.mas_bottom).offset(6);
        make.left.equalTo(self.nameL);
        make.right.lessThanOrEqualTo(self.card).offset(-16);
    }];

    // 统计区
    _statStack = [[UIStackView alloc] init];
    _statStack.axis = UILayoutConstraintAxisHorizontal;
    _statStack.alignment = UIStackViewAlignmentFill;
    _statStack.distribution = UIStackViewDistributionFillEqually;
    _statStack.spacing = 0;
    [_card addSubview:_statStack];
    [_statStack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.avatar.mas_bottom).offset(14);
        make.left.equalTo(self.card).offset(8);
        make.right.equalTo(self.card).offset(-8);
        make.bottom.equalTo(self.card).offset(-12);
        make.height.mas_equalTo(68);
    }];

    // 宫格功能
    UILabel *menuTitle = [self sectionTitle:@"功能服务"];
    [_content addSubview:menuTitle];
    [menuTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.card.mas_bottom).offset(18);
        make.left.equalTo(self.content).offset(16);
        make.right.equalTo(self.content).offset(-16);
    }];

    UICollectionViewFlowLayout *gridLayout = [[UICollectionViewFlowLayout alloc] init];
    gridLayout.minimumLineSpacing = 10;
    gridLayout.minimumInteritemSpacing = 10;

    _menuGrid = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:gridLayout];
    _menuGrid.backgroundColor = UIColor.clearColor;
    _menuGrid.scrollEnabled = NO;
    _menuGrid.dataSource = self;
    _menuGrid.delegate   = self;
    [_menuGrid registerClass:SMMineMenuCell.class forCellWithReuseIdentifier:kMenuCellId];
    [_content addSubview:_menuGrid];
    [_menuGrid mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(menuTitle.mas_bottom).offset(8);
        make.left.equalTo(self.content).offset(16);
        make.right.equalTo(self.content).offset(-16);
        // 先占一个最小高度，真正高度在 adjustGridItemSize 里动态算
        self.menuGridHeightConstraint = make.height.mas_equalTo(160);
    }];
    // 最近浏览
    _recentTitle = [self sectionTitle:@"最近浏览 / 猜你喜欢"];
    [_content addSubview:_recentTitle];
    [_recentTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.menuGrid.mas_bottom).offset(16);
        make.left.equalTo(self.content).offset(16);
        make.right.equalTo(self.content).offset(-16);
    }];

    UICollectionViewFlowLayout *hLayout = [[UICollectionViewFlowLayout alloc] init];
    hLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    hLayout.minimumLineSpacing = 12;
    hLayout.minimumInteritemSpacing = 12;
    hLayout.sectionInset = UIEdgeInsetsMake(0, 16, 0, 16);

    _recentList = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:hLayout];
    _recentList.backgroundColor = UIColor.clearColor;
    _recentList.showsHorizontalScrollIndicator = NO;
    _recentList.dataSource = self;
    _recentList.delegate   = self;
    [_recentList registerClass:SMMineRecentCell.class forCellWithReuseIdentifier:kRecentCellId];
    [_content addSubview:_recentList];
    [_recentList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.recentTitle.mas_bottom).offset(8);
        make.left.right.equalTo(self.content);
        make.height.mas_equalTo(160);
        make.bottom.equalTo(self.content.mas_bottom).offset(-24);
    }];
}

- (UILabel *)sectionTitle:(NSString *)txt {
    UILabel *l = [UILabel new];
    l.text = txt;
    l.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    l.textColor = UIColor.labelColor;
    return l;
}

- (void)addGradientTo:(UIView *)view {
    CAGradientLayer *g = [CAGradientLayer layer];
    g.colors = @[
        (id)[UIColor colorWithRed:0.27 green:0.55 blue:0.99 alpha:1].CGColor,
        (id)[UIColor colorWithRed:0.37 green:0.80 blue:0.89 alpha:1].CGColor
    ];
    g.startPoint = CGPointMake(0, 0);
    g.endPoint   = CGPointMake(1, 1);
    g.frame = view.bounds;
    g.name  = @"mine.header.gradient";
    [view.layer addSublayer:g];
    // 自适应尺寸变化
    view.layer.masksToBounds = YES;
    [view.layer.sublayers.firstObject setNeedsLayout];
    view.layer.needsDisplayOnBoundsChange = YES;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    for (CALayer *s in self.headerUnderlay.layer.sublayers) {
        if ([s.name isEqualToString:@"mine.header.gradient"]) {
            s.frame = self.headerUnderlay.bounds;
        }
    }
    // 同时保留你调整宫格 itemSize 的逻辑
    [self adjustGridItemSize];
}

#pragma mark - Data

- (void)mockDataAndRender {
    // 头像与昵称
    NSString *avatarURL = [NSString stringWithFormat:@"https://i.pravatar.cc/200?img=%d", arc4random_uniform(70)+1];
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:avatarURL]
                    placeholderImage:([UIImage imageNamed:@"avatar_placeholder"] ?: nil)];
    self.nameL.text = @"废钢小老板";
    self.signL.text = @"专注重废/剪切料，诚信经营，长期合作～";

    // 统计：收藏、关注、粉丝、浏览
    NSArray *stats = @[
        @{@"title":@"收藏", @"count":@(arc4random_uniform(200)+12), @"action":@"fav"},
        @{@"title":@"关注", @"count":@(arc4random_uniform(150)+5),  @"action":@"follow"},
        @{@"title":@"粉丝", @"count":@(arc4random_uniform(800)+30), @"action":@"fans"},
        @{@"title":@"浏览", @"count":@(arc4random_uniform(1200)+100),@"action":@"history"}
    ];
    [self.statStack.arrangedSubviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for (int i=0;i<stats.count;i++) {
        NSDictionary *d = stats[i];
        UIButton *btn = [self statButtonWithCount:[d[@"count"] integerValue] title:d[@"title"]];
        btn.tag = i;
        [btn addTarget:self action:@selector(tapStat:) forControlEvents:UIControlEventTouchUpInside];
        [self.statStack addArrangedSubview:btn];

        if (i<stats.count-1) {
            UIView *sep=[UIView new];
            sep.backgroundColor = [UIColor colorWithWhite:0 alpha:0.06];
            [self.statStack addArrangedSubview:sep];
            [sep mas_makeConstraints:^(MASConstraintMaker *make){
                make.width.mas_equalTo(1);
            }];
        }
    }

    // 宫格功能
    _menuData = @[
      @{@"title":@"我的订单", @"icon":@"cart"},
      @{@"title":@"地址管理", @"icon":@"location"},
      @{@"title":@"我的钱包", @"icon":@"creditcard"},
      @{@"title":@"消息中心", @"icon":@"bell"},
      @{@"title":@"浏览记录", @"icon":@"clock"},
      @{@"title":@"邀请好友", @"icon":@"gift"},
      @{@"title":@"客服帮助", @"icon":@"questionmark.circle"},
      @{@"title":@"关于我们", @"icon":@"info.circle"},
      @{@"title":@"设置",   @"icon":@"gearshape"}
    ];
    [self.menuGrid reloadData];

    // 最近浏览/猜你喜欢（网络图）
    NSMutableArray *arr=[NSMutableArray array];
    for (int i=0;i<12;i++){
        NSString *img = [NSString stringWithFormat:@"https://picsum.photos/seed/mine_recent_%d/300/200", i];
        NSString *title = @[@"重废",@"钢筋切粒",@"HMS1/2",@"机械冲片",@"钢板边角料",@"普中废"][arc4random_uniform(6)];
        [arr addObject:@{@"title":[NSString stringWithFormat:@"%@ · #%d", title, i+1], @"image":img}];
    }
    _recentData = arr;
    [self.recentList reloadData];

    // 触发一次布局以计算 contentSize
    [self.content setNeedsLayout];
    [self.content layoutIfNeeded];
}

- (UIButton *)statButtonWithCount:(NSInteger)count title:(NSString *)title {
    UIButton *b=[UIButton buttonWithType:UIButtonTypeCustom];
    b.adjustsImageWhenHighlighted = NO;

    UILabel *countL=[UILabel new];
    countL.font = [UIFont systemFontOfSize:18 weight:UIFontWeightSemibold];
    countL.text = [NSString stringWithFormat:@"%ld",(long)count];
    countL.textAlignment = NSTextAlignmentCenter;

    UILabel *titleL=[UILabel new];
    titleL.font = [UIFont systemFontOfSize:13];
    titleL.textColor = UIColor.secondaryLabelColor;
    titleL.text = title;
    titleL.textAlignment = NSTextAlignmentCenter;

    UIStackView *sv=[[UIStackView alloc] initWithArrangedSubviews:@[countL, titleL]];
    sv.axis = UILayoutConstraintAxisVertical;
    sv.alignment = UIStackViewAlignmentFill;
    sv.spacing = 2;

    [b addSubview:sv];
    [sv mas_makeConstraints:^(MASConstraintMaker *make){
        make.edges.equalTo(b);
    }];
    b.backgroundColor = UIColor.clearColor;
    return b;
}

#pragma mark - Actions

- (void)tapSettings {
    // TODO: push 设置页面
    UIAlertController *ac=[UIAlertController alertControllerWithTitle:@"设置" message:@"这里进入设置页面" preferredStyle:UIAlertControllerStyleAlert];
    [ac addAction:[UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:ac animated:YES completion:nil];
}

- (void)tapStat:(UIButton *)sender {
    NSArray *tips=@[@"我的收藏",@"我的关注",@"我的粉丝",@"浏览记录"];
    NSString *msg = tips[sender.tag];
    UIAlertController *ac=[UIAlertController alertControllerWithTitle:msg message:@"这里进入对应列表页" preferredStyle:UIAlertControllerStyleAlert];
    [ac addAction:[UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:ac animated:YES completion:nil];
}

#pragma mark - CollectionView

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.menuGrid) return self.menuData.count;
    return self.recentData.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (cv == self.menuGrid) {
        SMMineMenuCell *cell = [cv dequeueReusableCellWithReuseIdentifier:kMenuCellId forIndexPath:indexPath];
        NSDictionary *d = self.menuData[indexPath.item];
        [cell configureWithTitle:d[@"title"] symbol:d[@"icon"]];
        return cell;
    } else {
        SMMineRecentCell *cell = [cv dequeueReusableCellWithReuseIdentifier:kRecentCellId forIndexPath:indexPath];
        NSDictionary *d = self.recentData[indexPath.item];
        [cell configureWithTitle:d[@"title"] imageURL:d[@"image"]];
        return cell;
    }
}


#pragma mark - Collection Delegate (宫格点击)
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView != self.menuGrid) return;
    if (indexPath.item >= self.menuData.count) return;

    NSString *title = self.menuData[indexPath.item];
    if (![title isKindOfClass:NSString.class]) {
        // 兼容字典结构：@{@"title":@"消息中心", ...}
        NSDictionary *d = (NSDictionary *)self.menuData[indexPath.item];
        if ([d isKindOfClass:NSDictionary.class]) {
            title = d[@"title"] ?: @"";
        } else {
            title = @"";
        }
    }

    // 标题匹配跳转（覆盖我的页所有子入口）
    if ([title containsString:@"消息"]) {
        [self goToMessages];
    } else if ([title containsString:@"浏览"]) {
        [self goToHistory];
    } else if ([title containsString:@"邀请"]) {
        [self goToInvite];
    } else if ([title containsString:@"客服"] || [title containsString:@"帮助"]) {
        [self goToSupport];
    } else if ([title containsString:@"设置"]) {
        [self goToSettings];
    } else if ([title containsString:@"收藏"]) {
        [self goToFavorites];
    } else if ([title containsString:@"关注"]) {
        [self goToFollows];
    } else if ([title containsString:@"粉丝"]) {
        [self goToFans];
    } else if ([title containsString:@"订单"]) {
        [self goToOrders];
    } else if ([title containsString:@"地址"]) {
        [self goToAddress];
    } else if ([title containsString:@"钱包"]) {
        [self goToWallet];
    } else if ([title containsString:@"关于"]) {
        [self goToAbout];
    } else {
        // 兜底：未来再扩展其他入口，在这里加 else if 即可
    }

}

#pragma mark - 统一的 push 封装
- (void)sm_push:(UIViewController *)vc {
    if (!vc) return;
    vc.hidesBottomBarWhenPushed = YES; // 进入子页隐藏底部 Tab
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 子页跳转方法（给按钮/手势/宫格复用）
- (void)goToFavorites  { [self sm_push:[SMMineFavoritesViewController new]]; }
- (void)goToFollows    { [self sm_push:[SMMineFollowsViewController new]]; }
- (void)goToFans       { [self sm_push:[SMMineFansViewController new]]; }
- (void)goToOrders     { [self sm_push:[SMMineOrdersViewController new]]; }
- (void)goToAddress    { [self sm_push:[SMMineAddressViewController new]]; }
- (void)goToWallet     { [self sm_push:[SMMineWalletViewController new]]; }
- (void)goToMessages   { [self sm_push:[SMMineMessagesViewController new]]; }
- (void)goToHistory    { [self sm_push:[SMMineHistoryViewController new]]; }
- (void)goToInvite     { [self sm_push:[SMMineInviteViewController new]]; }
- (void)goToSupport    { [self sm_push:[SMMineSupportViewController new]]; }
- (void)goToAbout      { [self sm_push:[SMMineAboutViewController new]]; }
- (void)goToSettings   { [self sm_push:[SMMineSettingsViewController new]]; }
#pragma mark - Layout for cells

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self adjustGridItemSize];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    [self adjustGridItemSize];
}

- (void)adjustGridItemSize {
    CGFloat w = self.view.bounds.size.width - 32; // content 左右各 16
    UICollectionViewFlowLayout *gridLayout = (UICollectionViewFlowLayout *)self.menuGrid.collectionViewLayout;
    CGFloat spacing = gridLayout.minimumInteritemSpacing; // 10
    NSInteger col = 3;

    // ✅ cell 尺寸稍微加高一点，标题不会被挤没
    CGFloat itemW = floor((w - spacing * (col - 1)) / col);
    CGFloat itemH = 96; // 原来 90，略增高，标题更安全
    gridLayout.itemSize = CGSizeMake(itemW, itemH);

    // ⭐️ 动态求高度 = 行数 * itemH + (行数-1)*行间距
    NSInteger count = self.menuData.count;
    NSInteger rows  = (count + col - 1) / col;
    CGFloat lineSpacing = gridLayout.minimumLineSpacing; // 10
    CGFloat gridH = rows * itemH + MAX(0, rows - 1) * lineSpacing;

    // 更新约束
    [self.menuGridHeightConstraint uninstall];
    [self.menuGrid mas_updateConstraints:^(MASConstraintMaker *make) {
        self.menuGridHeightConstraint = make.height.mas_equalTo(gridH);
    }];

    // 最近浏览横向卡片尺寸
    UICollectionViewFlowLayout *hLayout = (UICollectionViewFlowLayout *)self.recentList.collectionViewLayout;
    hLayout.itemSize = CGSizeMake(200, 150);

    // 更新布局
    [self.view layoutIfNeeded];
}

@end
